package cn.zhangjie.controller;

import cn.zhangjie.domain.JsonResult;
import cn.zhangjie.domain.Product;
import cn.zhangjie.domain.Store;
import cn.zhangjie.mapper.ProductMapper;
import cn.zhangjie.storefenig.StoreFeignClient;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private StoreFeignClient storeFeignClient;
    @Autowired
    private ProductMapper productMapper;

    @PutMapping("/add")
    @SentinelResource(value="productadd",fallback = "fallbackOrderMethon")
    public JsonResult add(@RequestBody Product dto){
        try {
            Product product = new Product();
            String name = dto.getName();
            Integer number = dto.getNumber();
            Integer price = dto.getPrice();
            product.setName(name);
            product.setPrice(price);

            productMapper.add(product);
            Store store = new Store();
            store.setProduct_id(product.getId());
            store.setNumber(number);
            storeFeignClient.add(store);
            return JsonResult.me().setMsg("两个数据库添加成功了");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("ggggg");
        }
    }



    @GetMapping("/findone/{id}")
    @SentinelResource(value="productfindone",fallback="exceptionHandler")
    public Product findone(@PathVariable("id") Long id){
        return productMapper.findone(id);
    }

    @GetMapping("/findstore/{id}")
    @SentinelResource(value="productfindone",fallback="exceptionHandler")
    public Store findstore(@PathVariable("id") Long id){
        return storeFeignClient.findone(id);
    }

    // 限流与阻塞处理 : 参数要和 被降级的方法参数一样
    public Store exceptionHandler(@PathVariable Long id, BlockException ex) {
        ex.printStackTrace();
        System.out.println("触发熔断了");
        return new Store(id,-1l,-1);
    }

    public JsonResult fallbackOrderMethon(@RequestBody Product dto,Throwable e){
            e.printStackTrace();
            return JsonResult.me().setMsg("触发熔断了");
    }



}
